/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source: any) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj: any = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function hexToRgb(hex: string, opacity = 1) {
  hex = hex.replace(/^\s*#|\s*$/g, '')
  // 将三位十六进制转为六位
  if (hex.length === 3) {
    hex = hex.replace(/(.)/g, '$1$1')
  }

  // 提取R、G、B各自的十六进制表示方式
  // const rgb = /^(\w{2})(\w{2})(\w{2})$/.exec(hex)
  const r = parseInt(hex.substring(0, 2), 16)
  const g = parseInt(hex.substring(2, 4), 16)
  const b = parseInt(hex.substring(4, 6), 16)
  const obj = {
    r,
    g,
    b,
    rgb: `rgb(${r}, ${g}, ${b})`,
    rgba: `rgba(${r}, ${g}, ${b}, ${opacity})`,
  }
  return obj
}
